package com.echo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.AiManager.AiManager;
import com.echo.context.WisUserIdContext;
import com.echo.entity.Exam;
import com.echo.entity.ExamAnalysis;
import com.echo.entity.ExamRecord;
import com.echo.mapper.ExamAnalysisMapper;
import com.echo.mapper.ExamMapper;
import com.echo.mapper.ExamRecordMapper;
import com.echo.service.IExamAnalysisService;
import com.echo.vo.AllObjectDetailData;
import com.echo.vo.ExamIdAnaDataVo;
import com.echo.vo.ObjectDataVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.echo.constant.AIRole.*;

/**
 * <p>
 * AI生成的学生答题情况分析和反馈表 服务实现类
 * </p>
 *
 * @author echo
 * @since 2024-11-05
 */
@Service
public class ExamAnalysisServiceImpl extends ServiceImpl<ExamAnalysisMapper, ExamAnalysis> implements IExamAnalysisService {
    @Autowired
    private ExamAnalysisMapper examAnalysisMapper;
    @Autowired
    private AiManager aiManager;
    @Autowired
    private ExamServiceImpl examService;
    @Autowired
    private ExamRecordMapper examRecordMapper;
    @Autowired
    private ExamMapper examMapper;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    //这里的话去得到 一系列的key
    // 这里的话是分析用户某一科目的问题，所以是去得到某一科目
    //
    @Override
    public ObjectDataVo getObjectDatailData(String subject) {
        String userId = WisUserIdContext.getUserIdContext();
        QueryWrapper<ExamAnalysis> wrapper = new QueryWrapper<>();
        // 获取所有符合条件的分析结果
        // todo：这里的会对该学生不同试卷的去进行分析，保证是利用不同试卷去进行分析的
        wrapper.lambda()
                .select(ExamAnalysis::getPerformanceSummary, ExamAnalysis::getExamId, ExamAnalysis::getAttemptNumber)  // 选择需要的字段
                .eq(ExamAnalysis::getUserId, userId)
                .eq(ExamAnalysis::getExamType, subject);// 限定试卷类型为指定的科目
        List<ExamAnalysis> examAnalyses = examAnalysisMapper.selectList(wrapper);

        // 使用 Java Stream 按照 ExamId 分组并提取 AttemptNumber 最大的记录
        Map<String, ExamAnalysis> filteredExamAnalyses = examAnalyses.stream()
                .collect(Collectors.toMap(
                        ExamAnalysis::getExamId,  // 按照 ExamId 分组
                        Function.identity(),
                        (existing, replacement) -> existing.getAttemptNumber() >= replacement.getAttemptNumber() ? existing : replacement // 获取 AttemptNumber 最大的记录
                ));

        // 提取每个试卷中 AttemptNumber 最大的 PerformanceSummary
        List summaryList = filteredExamAnalyses.values().stream()
                .map(ExamAnalysis::getPerformanceSummary)
                .limit(30)  // 限制 summaryList 最多只包含 30 条记录
                .collect(Collectors.toList());

        // 如果没有找到任何结果，设置 summaryList 为 "null"
        if (summaryList.isEmpty()) {
            summaryList.add("null");
        }

    // 输出 summaryList 或进行其他逻辑操作
        System.out.println("试卷的总结集合: " + summaryList);
    // 这里将list集合转为json串
        String summaryListJson = convertListToJson(summaryList);
    // 构建词
    // 构建请求的 JSON 字符串，包含科目和历史评价列表
        String analysisRequestJson = String.format("{\"subject\": \"%s\", \"historySummary\": %s}", subject, summaryListJson);
        // 这里调用ai 去得到分析结果
        // 这里去调用ai 去得到分析的结果
        String analysis_old = aiManager.doSyncStableRequest(GENERATE_OBJECT_DATA_SYSTEM_MESSAGE, analysisRequestJson);
        int start = analysis_old.indexOf("{");
        int end = analysis_old.lastIndexOf("}");
        //这里得到ai返回的结果
        String analysis = analysis_old.substring(start, end + 1);
        try {
            JsonNode root = objectMapper.readTree(analysis);

            // 得到薄弱点分析
            List<String> weakPointsList = new ArrayList<>();
            root.path("weakPoints").forEach(node -> weakPointsList.add(node.asText()));
            String weakPoints = String.join(", ", weakPointsList);

        // 提取 knowledgePoints 数据
            List<Map<String, String>> knowData = new ArrayList<>();
            double totalMastery = 0.0;

        // 第一遍遍历，累加所有的 mastery
            for (JsonNode node : root.path("knowledgePoints")) {
                totalMastery += node.path("mastery").asDouble();
            }

        // 按总和重新计算并存储 knowledgePoints
            if (totalMastery > 0) {
                double finalTotalMastery = totalMastery;
                root.path("knowledgePoints").forEach(node -> {
                    Map<String, String> knowledgePoint = new HashMap<>();
                    knowledgePoint.put("name", node.path("name").asText());

                    // 重新计算 mastery 的比例
                    double normalizedMastery = node.path("mastery").asDouble() / finalTotalMastery;
                    knowledgePoint.put("mastery", String.format("%.4f", normalizedMastery)); // 保留4位小数

                    // 添加到 knowledgePoints 列表中
                    knowData.add(knowledgePoint);
                });
            } else {
                // 如果 totalMastery 为 0，设置所有掌握度为 0
                root.path("knowledgePoints").forEach(node -> {
                    Map<String, String> knowledgePoint = new HashMap<>();
                    knowledgePoint.put("name", node.path("name").asText());
                    knowledgePoint.put("mastery", "0.0000"); // 如果总和为0，则所有 mastery 都为0
                    knowData.add(knowledgePoint);
                });
            }

            // 构造返回对象
            ObjectDataVo objectDataVo = new ObjectDataVo();
            objectDataVo.setKnowledgeData(knowData);
            objectDataVo.setWeakPoints(weakPointsList);

            return objectDataVo;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //对同一张卷子的分析
    @Override
    public ExamIdAnaDataVo getExamIdAnalysisData(String examId) throws IOException {
        // todo:修改：1.这里的数据都是有问题的：1.考试得分 总分 2.知识点掌握情况的百分比[换一下提示词】，3.历史掌握情况的数值【这里用准确率去替换即可】
        String userId = WisUserIdContext.getUserIdContext();
        System.out.println(examId==null);
        System.out.println(examId.equals("null"));
        if(examId=="null"||examId.equals("null")){
            QueryWrapper<ExamRecord> getExamId=new QueryWrapper<>();
            getExamId.lambda()
                    .orderByDesc(ExamRecord::getCreatTime)
                    .last("LIMIT 1");
            ExamRecord examRecord = examRecordMapper.selectOne(getExamId);
            System.out.println(examRecord);
            examId = examRecord.getExamId();
        }
        QueryWrapper<ExamRecord> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ExamRecord::getExamJoinerId, userId)
                .eq(ExamRecord::getExamId, examId)
                .orderByDesc(ExamRecord::getCreatTime)
                .last("LIMIT 10");

        // 获取历史答题情况
        List<ExamRecord> examRecords = examRecordMapper.selectList(wrapper);

        // 获取历史答题情况和准确率，并生成 List<Map<String, String>>
        List<Map<String, String>> queCorUserAnsJson = new ArrayList<>();
        List<Integer> scoreList=new ArrayList<>();
        for (ExamRecord examRecord : examRecords) {
            String answer = examRecord.getAnaQue();
            String name = examRecord.getExamType();
            if (answer != null && name != null) {
                Map<String, String> map = new HashMap<>();
                map.put(name, answer);
                queCorUserAnsJson.add(map);
                scoreList.add(examRecord.getExamJoinScore());
            }
        }
        //历史掌握情况的 根据得分来的
        List<Map<String, Integer>> periodicMasteryListScore = new ArrayList<>();
// 转换为指定的 JSON 格式，并加上答题次数标记
        List<Map<String, Object>> formattedData = new ArrayList<>();
        int attemptCounter = 1;  // 记录答题次数

        for (Map<String, String> map : queCorUserAnsJson) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String name = entry.getKey();  // 获取科目名称
                String answer = entry.getValue();  // 获取答题情况

                // 将答题情况解析为 JsonNode 数组
                JsonNode questionsNode = objectMapper.readTree(answer);

                // 构建科目和题目列表的 Map
                Map<String, Object> subjectMap = new HashMap<>();
                subjectMap.put("考试名称", name);
                subjectMap.put("questions", questionsNode);  // 存入解析后的题目 JSON 数据
                subjectMap.put("attempt", "第" + attemptCounter + "次");  // 加入答题次数标记
                subjectMap.put("Score", "得分为" + scoreList.get(attemptCounter-1) );  // 加入答题次数标记
                Map<String, Integer> perMap=new HashMap<>();
                perMap.put("第" + attemptCounter + "次",scoreList.get(attemptCounter-1));
                periodicMasteryListScore.add(perMap);
                // 添加到最终结果
                formattedData.add(subjectMap);
            }
            attemptCounter++;  // 每次答题记录次数增加
        }

// 转换为 JSON 字符串
        String jsonArrayString = objectMapper.writeValueAsString(formattedData);
        System.out.println("JSON 格式的多次答题记录: " + jsonArrayString);
// 调用 AI 获取分析数
        System.out.println("jsonArrayString"+jsonArrayString);
        // 调用 AI 获取分析数据
        String analysisData = aiManager.doSyncStableRequest(GENERATE_PERIODIC_MASTERY_ANALYSIS_MESSAGE, jsonArrayString);
        int start = analysisData.indexOf("{");
        int end = analysisData.lastIndexOf("}");
        System.out.println(analysisData);
        // 确保返回数据包含 JSON 格式
        if (start == -1 || end == -1) {
            return new ExamIdAnaDataVo();  // 返回空对象，表示 AI 返回数据无效
        }

        String analysis = analysisData.substring(start, end + 1);
        // 得到详细的分析·结果

        JsonNode root = objectMapper.readTree(analysis);

        // 解析 subject
        String subject = root.path("subject").asText(null);  // 设置默认值为 null
        System.out.println("科目名称: " + (subject != null ? subject : "未知科目"));
        //todo：这里改改
        // 解析 periodicMastery 为 List<Map<String, Integer>>
        List<Map<String, Integer>> periodicMasteryList = new ArrayList<>();
        JsonNode periodicMasteryNode = root.path("periodicMastery");
        double totalMastery = 0.0; // 用于计算 periodicMastery 的总和

        if (periodicMasteryNode != null && periodicMasteryNode.isObject()) {
            Iterator<Map.Entry<String, JsonNode>> masteryFields = periodicMasteryNode.fields();
            while (masteryFields.hasNext()) {
                Map.Entry<String, JsonNode> entry = masteryFields.next();
                if (entry.getValue() != null && entry.getValue().isNumber()) {
                    double masteryValue = entry.getValue().asDouble();
                    totalMastery += masteryValue;  // 累加计算总和
                    Map<String, Integer> masteryMap = new HashMap<>();
                    masteryMap.put(entry.getKey(), (int)masteryValue); // 初步转换为整数百分比
                    periodicMasteryList.add(masteryMap);
                }
            }
        }
        // 限制结果只保留 10 条数据
        if (periodicMasteryList.size() > 10) {
            periodicMasteryList = periodicMasteryList.subList(0, 10);
        }
        System.out.println("periodicMasteryList"+periodicMasteryNode
        );

        /*// 重新计算 periodicMasteryList，使其总和为1
        if (totalMastery > 0) {
            for (Map<String, Integer> masteryMap : periodicMasteryList) {
                String key = masteryMap.keySet().iterator().next();
                double normalizedValue = masteryMap.get(key) / (totalMastery * 100);  // 归一化处理
                masteryMap.put(key, (int) (normalizedValue * 100));  // 转换为新的整数百分比
            }
        }*/
        //不使用上面计算的了 使用根据得分来的历史情况
        periodicMasteryList=periodicMasteryListScore;
        System.out.println("归一化后的不同时期历史掌握情况: " + periodicMasteryList);

        // 解析 knowledgePoints 为 List<Map<String, Integer>>
        List<Map<String, Integer>> knowledgePointsList = new ArrayList<>();
        JsonNode knowledgePointsArray = root.path("knowledgePoints");
        double totalKnowledgeMastery = 0.0;  // 用于计算 knowledgePoints 的总和

        // 第一遍遍历，解析数据并计算总和
        if (knowledgePointsArray != null && knowledgePointsArray.isArray()) {
            for (JsonNode knowledgePointNode : knowledgePointsArray) {
                if (knowledgePointNode.has("name") && knowledgePointNode.has("mastery")) {
                    String name = knowledgePointNode.path("name").asText(null);
                    String masteryString = knowledgePointNode.path("mastery").asText();

                    if (name != null && masteryString != null) {
                        try {
                            // 将字符串形式的 mastery 转换为 double
                            double masteryValue = Double.parseDouble(masteryString);
                            totalKnowledgeMastery += masteryValue;  // 累加计算总和

                            // 初步解析为 Map 但不归一化
                            Map<String, Integer> knowledgeMap = new HashMap<>();
                            knowledgeMap.put(name, (int) (masteryValue * 100));  // 先存为整数百分比
                            knowledgePointsList.add(knowledgeMap);
                        } catch (NumberFormatException e) {
                            System.err.println("无法解析 mastery 值为数字: " + masteryString);
                        }
                    }
                }
            }
        }


        System.out.println("归一化后的 knowledgePointsList: " + knowledgePointsList);
        // 这里调用另一个分析得到examAnalsis的分析结果
        //todo:这里有点缺陷，只采取1了查询时间最近的去分析，这里可以改为所有的
        QueryWrapper<ExamRecord> wrapperRecore=new QueryWrapper<>();
        wrapperRecore.lambda().eq(ExamRecord::getExamId,examId)
                        .eq(ExamRecord::getExamJoinerId,userId)
                .orderByDesc(ExamRecord::getExamJoinDate)  // 按时间字段降序排列
                .last("LIMIT 1");  // 取最新的一条记录
        ExamRecord examRecord = examRecordMapper.selectOne(wrapperRecore);
        String anaQues = examRecord.getAnaQue();
        Integer totalScore = examRecord.getExamJoinScore();
        System.out.println("anaQues"+anaQues);
        // 重新解析为 List<Map<Map<String, String>, String>> 类型
        // 定义最终的目标结构
        // 先将 JSON 字符串解析为 JsonNode
        JsonNode rootNode = objectMapper.readTree(anaQues);

        // 定义最终的目标结构
        List<Map<Map<String, String>, String>> parsedAnsQue = new ArrayList<>();
        // 遍历每个 JsonNode
        if (rootNode.isArray()) {
            for (JsonNode node : rootNode) {
                Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> field = fields.next();
                    String key = field.getKey();
                    String value = field.getValue().asText();

                    // 将复杂键字符串（例如 "{测试用户=答案1. 分的积分}"）进行解析
                    String cleanedKey = key.replaceAll("[{}]", "");  // 去掉大括号
                    String[] keyParts = cleanedKey.split("=", 2);  // 使用等号分割

                    if (keyParts.length == 2) {
                        String innerKey = keyParts[0].trim();   // 内层的键
                        String innerValue = keyParts[1].trim(); // 内层的值

                        // 构造内层 Map
                        Map<String, String> innerMap = new HashMap<>();
                        innerMap.put(innerKey, innerValue);

                        // 构造外层 Map
                        Map<Map<String, String>, String> outerMap = new HashMap<>();
                        outerMap.put(innerMap, value);

                        // 添加到最终列表中
                        parsedAnsQue.add(outerMap);
                    }
                }
            }
        }
        QueryWrapper<Exam> examQueryWrapper=new QueryWrapper<>();
        examQueryWrapper.lambda()
                        .eq(Exam::getExamId,examId);
        Exam exam = examMapper.selectOne(examQueryWrapper);
        Integer examScore = exam.getExamScore();
        double rate;
        if (totalScore==0||examScore==0){
            rate=0;
        }else {
            rate = (double) totalScore / examScore;
        }

        ExamAnalysis examAnalysis = examService.analysisAnsQue(parsedAnsQue, examId, rate, totalScore,false,"-1");

        // 构建返回对象
        ExamIdAnaDataVo examIdAnaDataVo = new ExamIdAnaDataVo();
        examIdAnaDataVo.setKnowledgePointsList(knowledgePointsList);
        examIdAnaDataVo.setPeriodicMasteryList(periodicMasteryList);
        examIdAnaDataVo.setExamAnalysis(examAnalysis);
        return examIdAnaDataVo;
    }
    //综合分析
    //1.不同科目的掌握程度【这里对不同科目进行分流，保证每一科目都至少有10条数据】
    //2.做题时间的频率分析
    //3.统计不同科目的正确率分析
    //4.统计所有用户的 【1.不同科目之间/综合】
    // 4.1正确率分析，并且得出当前用户在哪个位置
    // 4.2 综合的话·就是分析
    //4.返回评价信息和总结
    @Override
    public AllObjectDetailData getAllObjectDetailData() throws JsonProcessingException {
        String userId = WisUserIdContext.getUserIdContext();
        QueryWrapper<ExamAnalysis> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ExamAnalysis::getUserId, userId)
                .orderByDesc(ExamAnalysis::getCreateTime); // 按创建时间降序，确保获取最新的记录

        // 获取所有历史答题情况
        List<ExamAnalysis> examAnalyses = examAnalysisMapper.selectList(wrapper);

        // 创建用于存储每个学科的最新评价总结列表
        Map<String, List<ExamAnalysis>> subjectToExamAnalysisMap = new HashMap<>();

        // 1. 按学科分组
        for (ExamAnalysis examAnalysis : examAnalyses) {
            String subject = examAnalysis.getExamType();
            if (subject != null) {
                subjectToExamAnalysisMap
                        .computeIfAbsent(subject, k -> new ArrayList<>())
                        .add(examAnalysis);
            }
        }

        // 2. 对每个学科的列表按创建时间排序，并只保留最新的10条记录
        Map<String, List<ExamAnalysis>> subjectToTop10ExamAnalysisMap = new HashMap<>();
        for (Map.Entry<String, List<ExamAnalysis>> entry : subjectToExamAnalysisMap.entrySet()) {
            String subject = entry.getKey();
            List<ExamAnalysis> analyses = entry.getValue();

            // 按时间降序排序
            analyses.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));

            // 取前10条记录
            List<ExamAnalysis> top10Analyses = analyses.size() > 10 ? analyses.subList(0, 10) : analyses;
            subjectToTop10ExamAnalysisMap.put(subject, top10Analyses);
        }

// 3. 创建最终的评价总结并构造成指定的 JSON 格式
        List<Map<String, Object>> formattedData = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        for (Map.Entry<String, List<ExamAnalysis>> entry : subjectToTop10ExamAnalysisMap.entrySet()) {
            String subject = entry.getKey();
            List<ExamAnalysis> analyses = entry.getValue();

            for (ExamAnalysis analysis : analyses) {
                String answer = analysis.getQueCorrectUserAns();
                if (answer != null) {
                    // 将答题情况解析为 JsonNode 数组
                    JsonNode questionsNode = objectMapper.readTree(answer);
                    int score= analysis.getExamScore();
                    //todo：1.这里没有提示说是第几条记录
                    // 构建科目和题目列表的 Map
                    // todo:2.20
                    Map<String, Object> subjectMap = new HashMap<>();
                    subjectMap.put("subject", subject);
                    subjectMap.put("questions", questionsNode);  // 存入解析后的题目 JSON 数据
                    subjectMap.put("ExamScore", score);  // 存入解析后的题目 JSON 数据
                    formattedData.add(subjectMap);
                }
            }
        }

// 转换为 JSON 字符串
        String jsonArrayString = objectMapper.writeValueAsString(formattedData);

// 输出 JSON 字符串或继续后续的逻辑操作
        System.out.println("不同学科的评价总结的JSON格式: " + jsonArrayString);
        System.out.println(jsonArrayString);
        String analysis_old = aiManager.doSyncStableRequest(GENERATE_SUBJECT_MASTERY_WITH_WEAKNESS_ANALYSIS_MESSAGE, jsonArrayString);
        int start = analysis_old.indexOf("{");
        int end = analysis_old.lastIndexOf("}");
        //这里得到ai返回的结果
        String analysis = analysis_old.substring(start, end + 1);
        // 创建 ObjectMapper 实例
        JsonNode root = objectMapper.readTree(analysis);
        // 解析 subjectMastery 为 List<Map<String, Double>>
        List<Map<String, Double>> subjectMasteryList = new ArrayList<>();
        JsonNode subjectMasteryNode = root.path("subjectMastery");
        Iterator<Map.Entry<String, JsonNode>> masteryFields = subjectMasteryNode.fields();
        while (masteryFields.hasNext()) {
            Map.Entry<String, JsonNode> entry = masteryFields.next();

            Map<String, Double> masteryMap = new HashMap<>();
            masteryMap.put(entry.getKey(), entry.getValue().asDouble());

            subjectMasteryList.add(masteryMap);  // 将单科目掌握度添加到列表中
        }
        System.out.println("科目掌握情况: " + subjectMasteryList);

        // 解析 weakSubjects 为 List<String>
        List<String> weakSubjects = new ArrayList<>();
        JsonNode weakSubjectsNode = root.path("weakSubjects");
        if (weakSubjectsNode.isArray()) {
            for (JsonNode subjectNode : weakSubjectsNode) {
                weakSubjects.add(subjectNode.asText());
            }
        }
        System.out.println("薄弱科目: " + weakSubjects);

        // 解析 suggestedReviewTopics 为 List<String>
        List<String> suggestedReviewTopics = new ArrayList<>();
        JsonNode reviewTopicsNode = root.path("suggestedReviewTopics");
        if (reviewTopicsNode.isArray()) {
            for (JsonNode topicNode : reviewTopicsNode) {
                suggestedReviewTopics.add(topicNode.asText());
            }
        }
        System.out.println("改进建议: " + suggestedReviewTopics);
        //得到评论总结
        String performanceSummary = root.path("performanceSummary").asText();
        //2.用户做题时间的频率分析
        QueryWrapper<ExamAnalysis> examRecordQueryWrapper=new QueryWrapper<>();
        examRecordQueryWrapper.lambda()
                .eq(ExamAnalysis::getUserId,userId);
        List<ExamAnalysis> examAnalysisList = examAnalysisMapper.selectList(examRecordQueryWrapper);
        List<LocalDateTime> localDateTimeList=new ArrayList<>();
        for (ExamAnalysis examAnalysis : examAnalysisList) {
            LocalDateTime createTime = examAnalysis.getCreateTime();
            localDateTimeList.add(createTime);
        }
        // 按小时统计用户做题次数
        Map<LocalDateTime, Integer> frequencyMap = localDateTimeList.stream()
                .collect(Collectors.toMap(
                        dateTime -> dateTime.withMinute(0).withSecond(0).withNano(0), // 使用小时作为键
                        dateTime -> 1, // 每次出现记为 1
                        Integer::sum // 如果有重复键，将值累加
                ));
        // 将统计结果转换为 List<Map<LocalDateTime, Integer>> 格式
        List<Map<LocalDateTime, Integer>> timeAttempt = new ArrayList<>();
        for (Map.Entry<LocalDateTime, Integer> entry : frequencyMap.entrySet()) {
            LocalDateTime hour = entry.getKey();
            Integer frequency = entry.getValue();

            Map<LocalDateTime, Integer> map = new HashMap<>();
            map.put(hour, frequency);
            timeAttempt.add(map);
        }
        //用户不同科目的答题正确率，先得到每一个科目的正确率，然后取平均
        List<String> examTypes = examService.getExamTypes();
        System.out.println("emtypes"+examTypes);
        List<Map<String,BigDecimal>> rates=new ArrayList<>();
        for (String examType : examTypes) {
            BigDecimal total= BigDecimal.valueOf(0.0);
            examRecordQueryWrapper.lambda()
                    .eq(ExamAnalysis::getUserId,userId)
                    .eq(ExamAnalysis::getExamType,examType);
            List<ExamAnalysis> examAnalysesType = examAnalysisMapper.selectList(examRecordQueryWrapper);
            if(examAnalysesType.size()==0){
                System.out.println();
                Map<String, BigDecimal> map=new HashMap<>();
                map.put(examType, BigDecimal.valueOf(0.00));
                rates.add(map);
                break;
            }
            for (ExamAnalysis examAnalysis : examAnalysesType) {
                BigDecimal correctRate = examAnalysis.getCorrectRate();
                System.out.println("correctRate"+correctRate);
                total.add(correctRate);
            }
            System.out.println("total"+total);
            BigDecimal result = total.divide(BigDecimal.valueOf(examAnalysesType.size()), 2, RoundingMode.HALF_UP);
            System.out.println("result"+result);
            Map<String, BigDecimal> map=new HashMap<>();
            map.put(examType,result);
            System.out.println(map);
            rates.add(map);
        }
        System.out.println();
        AllObjectDetailData allObjectDetailData=new AllObjectDetailData();
        allObjectDetailData.setWeakSubjects(weakSubjects);
        allObjectDetailData.setSubjectMasteryList(subjectMasteryList);
        allObjectDetailData.setSuggestedReviewTopics(suggestedReviewTopics);
        allObjectDetailData.setPerformanceSummary(performanceSummary);
        allObjectDetailData.setTimeAttempt(timeAttempt);
        allObjectDetailData.setTypeRates(rates);
        return allObjectDetailData;
    }




    public static String convertListToJson(List<String> summaryList) {
        try {
            // 将 List<String> 转换为 JSON 数组格式的字符串
            return objectMapper.writeValueAsString(summaryList);
        } catch (Exception e) {
            e.printStackTrace();
            return "[]"; // 返回空 JSON 数组字符串以确保不会传递空值
        }
    }

}
